/**
 * Complex class
 *
 * @author lyz
 * @date 2019/04/14
 */

package examinefour;
public class Complex {
    /**定义属性并生成getter,setter*/
    double realPart;
    double imagePart;
    /**定义构造函数*/
    public Complex(){
        realPart =0;
        imagePart =0;
    }
    public Complex(double r,double i){
        realPart =r;
        imagePart =i;
    }

    /**Override Object*/
    @Override
    public boolean equals(Object obj){
        if(obj instanceof Complex){
            if (doubleFormat(((Complex) obj).imagePart).equals(doubleFormat(this.imagePart))
                    && doubleFormat(((Complex) obj).realPart).equals(doubleFormat(this.realPart))){
                return true;
            }
            else {
                return false;
            }
        }
        else {
            return false;
        }
    }
    @Override
    public String toString(){
        if (this.imagePart >0) {
            return doubleFormat(this.realPart)+"+"+doubleFormat(this.imagePart)+"i";
        }else if(this.imagePart <0){
            return doubleFormat(this.realPart)+""+doubleFormat(this.imagePart)+"i";
        }else {
            return doubleFormat(this.realPart);
        }
    }

    /**定义公有方法:加减乘除*/
    Complex complexAdd(Complex a){
        double realresult;
        double imageresult;
        realresult = this.realPart +a.realPart;
        imageresult = this.imagePart +a.imagePart;
        return new Complex(realresult,imageresult);
    }
    Complex complexSub(Complex a){
        double realresult;
        double imageresult;
        realresult = this.realPart -a.realPart;
        imageresult = this.imagePart -a.imagePart;
        return new Complex(realresult,imageresult);
    }
    Complex complexMulti(Complex a){
        double realresult;
        double imageresult;
        realresult = this.realPart *a.realPart -this.imagePart *a.imagePart;
        imageresult = this.realPart *a.imagePart +this.imagePart *a.realPart;
        return new Complex(realresult,imageresult);
    }
    Complex complexDiv(Complex a) throws ComplexDivideZeroException{
        double realresult;
        double imageresult;
        if (a.imagePart ==0 && a.realPart ==0){
            throw new ComplexDivideZeroException("除数不能为0");
        }
        realresult = (this.realPart *a.realPart +this.imagePart *a.imagePart)/
                (a.imagePart *a.imagePart +a.realPart *a.realPart);
        imageresult = (this.imagePart *a.realPart -this.realPart *a.imagePart)/
                (a.imagePart *a.imagePart +a.realPart *a.realPart);
        return new Complex(realresult,imageresult);
    }

    String doubleFormat(double num){
        return String.format("%.2f",num);
    }
}